import sys
import threading
import time

import numpy as np
import tkinter as tk
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


class DynamicChart:
    def __init__(self, parent, interval, frames, row, column, span, lineNums,lstLabels):
        self.parent = parent
        self.frames = frames
        self.fig,self.ax = plt.subplots()
        self.fig.set_size_inches(7,2)
        # 初始化数据
        self.xdata = []
        self.ydata = [[]]
        self.index = 0

        self.lines = []
        for c in range(lineNums):
            self.lines.append(self.ax.plot([], [], label=lstLabels[c-1])[0])
            self.ydata.append([])
        self.ax.set_xlim(0, frames)
        self.ax.set_ylim(0, frames)
        self.ax.legend()

        # 创建图形画布
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.parent)

        #self.canvas.get_tk_widget().grid(row=row, column=column, columnspan=span)
        self.canvas.get_tk_widget().pack(fill=tk.X)

        self.appendData = [0]*lineNums

        # 启动动画更新函数
        self.ani = FuncAnimation(self.fig,
                                 self.update,
                                 interval=interval,
                                 frames=frames,
                                 init_func=self.init_plot,
                                 blit=False)

    def put(self, *datas):
        self.appendData=datas

    def init_plot(self):
        j = 0
        while j < len(self.lines):
            self.lines[j].set_data([], [])
            j += 1
        return self.lines

    def update(self, i):
        self.xdata.append(self.index)

        j = 0
        while j < len(self.lines):
            self.ydata[j].append(self.appendData[j])
            self.lines[j].set_data(self.xdata, self.ydata[j])
            j += 1

        # 动态更新X轴范围
        if len(self.xdata) > self.frames:
            self.ax.set_xlim(self.xdata[-self.frames], self.xdata[-1])
        else:
            self.ax.set_xlim(0, self.xdata[-1])
        # 动态更新Y轴范围
        j = 0
        minY=sys.maxsize
        maxY=-sys.maxsize
        while j < len(self.lines):
            if min(self.ydata[j]) < minY:
                minY = min(self.ydata[j])
            if max(self.ydata[j]) > maxY:
                maxY = max(self.ydata[j])
            j += 1
        self.ax.set_ylim(minY-5, maxY + 5)
        self.index += 1
        return self.lines
